const enterpriseVue = new Vue({
    el: '#app',
    data() {
      return {
        rules: [],
        form: {
          Group_Block_SerialNumber:'',
          Group_Block_Name:'',
          Picture_URL:'',
          Children:{
            group_block_detail:[] 
          }
        },
        Icon:[],
        Parent: [],
        children: '否',
        loading: false,
        isParent: true,
        isUrl:false,
        pic2:''
      }
    },
    mounted() {
      this.getIcon()
      const Group_Block_SerialNumber = sessionStorage.getItem("Group_Block_SerialNumber") 
      this.getData(Group_Block_SerialNumber) 
      this.uploadFront()
      this.uploadFront2()
    },
    methods: {
      getData(Group_Block_SerialNumber){
        const _this = this;
        $.ajax({
          url: DomainName + '/getSubtableInquiryOriginal?token='+ $.cookie('token'),
          type: 'POST',
          data:{
            Primary_Key:Group_Block_SerialNumber,
            JSONObject:JSON.stringify({group_block_info:{group_block_detail:{}}})
          },
          success: function (res) {
            _this.form = res.group_block_info[0]
            if(_this.form.Picture_URL == ''){
              _this.children = '是'
              _this.isUrl = true
            }
          },
          error: function () {
            _this.$message.error("操作失败，请稍后再试")
          },
          complete: function (XMLHttpRequest) {
            if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
              window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
            }
          }
        })
      },
      getIcon(){
        const _this = this;
        $.ajax({
          url: '../../../js/Icon.json',
          type: 'GET',
          success: function (data) {
            _this.Icon = data
          },
        })
      },
      getUrl(e){
        if(e === '是'){
          this.isUrl = true
          this.form.Picture_URL = ''
        }else if(e === '否'){
          this.isUrl = false
        }
      },
      submitForm(formName) {
        let _this = this
        this.$refs[formName].validate((valid) => {
          if (valid) {
            _this.loading = true
            const { add, modify } = _this.deal()
            let data = {}
            if (add == null) {
              data = { Data: JSON.stringify({ Modify: { group_block_info: [modify] } })}
            } else {
              data = { Data: JSON.stringify({ Modify: { group_block_info: [modify] }, Add: { group_block_info: [add], }}),}
            }
            $.ajax({
              url: `${DomainName}/getEditAction?token=${$.cookie("token")}`,
              type: 'POST',
              data,
              success: function (res) {
                if (res.Status === 'success') {
                  _this.$message.success("提交成功")
                  window.history.go(-1)
                } else {
                  _this.$message.error("提交失败，请稍后再试")
                }
              },
              error: function () {
                _this.$message.error("操作失败，请稍后再试")
              },
              complete: function (XMLHttpRequest) {
                _this.loading = false
                if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                  window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                }
              }
            })
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
      deal() {
        const add = deepClone(this.form)
        const modify = deepClone(this.form)
        let add_system_model_mark = [], modify_system_model_mark = []
  
        for (const i in modify.Children.group_block_detail) {
          const obj = modify.Children.group_block_detail[i];
          if (!Object.keys(obj).some(item => item.includes('_Original'))) {
            add_system_model_mark.push(obj)
          } else {
            modify_system_model_mark.push(obj)
          }
        }
        
        add.Children.group_block_detail = add_system_model_mark
        modify.Children.group_block_detail = modify_system_model_mark
  
        if (add_system_model_mark.length == 0) {
          return { add: null, modify };
        }
        return { add, modify };
      },
      add_system_model_mark(){
        this.form.Children.group_block_detail.push({
          Group_Block_Detail_SerialNumber:'',
          Group_Block_Detail_Name:'',
          Group_Block_SerialNumber:this.form.Group_Block_SerialNumber,
          Path:'',
          Icon:''

        })
        
      },
      remove_system_model_mark(){
        if (this.form.Children.group_block_detail.filter(item => item.Row_Status != '1').length > 0) {
          let i = this.form.Children.group_block_detail.filter(item => item.Row_Status != '1').length - 1
          let obj = this.form.Children.group_block_detail.filter(item => item.Row_Status != '1')[i]
          if (!Object.keys(obj).some(item => item.includes('_Original'))) {
            this.form.Children.group_block_detail.pop()
          } else {
            this.$confirm('警告！此操作将删除一条权限标识,可能会引起页面问题, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }).then(() => {
              this.form.Children.group_block_detail.filter(item => item.Row_Status != '1')[i].Row_Status = '1'
            }).catch(() => {
              this.$message({
                type: 'warning',
                message: '已取消删除'
              });
            });
          }
        }else{
          this.$message({
            message: '不能在删除了',
            type: 'warning'
          })
        }
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
        //商品封面图片
    uploadFront(file) {
      console.log('上传第一张图片')
      let _this = this
      let num = 1
      new Compressor(file, {
        quality: num,
        success(file) {
          console.log(file.size)
          const formData = new FormData();
          formData.append('file', file, file.name);
          let oFileReader = new FileReader();
          oFileReader.readAsDataURL(file);
          oFileReader.onload = function (e) {
            $.ajax({
              type: 'POST',
              url: DomainName + '/FileList',
              data: {
                Data: e.target.result,
                DataLength: file.size,
                FileName: file.name
              },
              complete: function (XMLHttpRequest) {
                _this.loading = false
                if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                  window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                }
              },
              success: function (Result) {
                _this.pic = e.target.result
                if (Result.Status == "success") {
                  _this.form.Picture_URL = Result.Picture_Url
                  _this.$message.success('上传成功')
                  console.log(Result.Picture_Url);
                } else {
                  _this.$message.error('上传失败')
                }
              },
              error: function () {
                _this.$message.error("操作失败，请稍后再试")
              },
              dataType: "json"
            });
          }
        },
        error(err) {
          console.log(err.message);
        },
      });
    },
    handleRemove(id){
      if(id=='1'){
        this.form.Picture_URL = '';
      }else{
        this.form.Details_URL = '';
      }
    },
    handlePictureCardPreview(url){
      this.dialogVisible = true
      this.dialogImageUrl = url
    },
       //商品封面图片
       uploadFront2(file2) {
        console.log('上传第二张图片')
        let _this = this
        let num = 1
        new Compressor(file2, {
          quality: num,
          success(file2) {
            console.log(file2.size)
            const formData = new FormData();
            formData.append('file', file2, file2.name);
            let oFileReader = new FileReader();
            oFileReader.readAsDataURL(file2);
            oFileReader.onload = function (e) {
              $.ajax({
                type: 'POST',
                url: DomainName + '/FileList',
                data: {
                  Data: e.target.result,
                  DataLength: file2.size,
                  FileName: file2.name
                },
                complete: function (XMLHttpRequest) {
                  _this.loading = false
                  if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                    window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                  }
                },
                success: function (Result) {
                  _this.form.Children.group_block_detail.Icon= e.target.result
                  if (Result.Status == "success") {
                    _this.form.Details_URL = Result.Picture_Url
                    _this.$message.success('上传成功')
                    console.log(Result.Picture_Url);
                  } else {
                    _this.$message.error('上传失败')
                  }
                },
                error: function () {
                  _this.$message.error("操作失败，请稍后再试")
                },
                dataType: "json"
              });
            }
          },
          error(err) {
            console.log(err.message);
          },
        });
      },
      handleRemove(id){
        if(id=='1'){
          this.form.Picture_URL = '';
        }else{
          this.form.Details_URL = '';
        }
      },
      handlePictureCardPreview(url){
        this.dialogVisible = true
        this.dialogImageUrl = url
      },
    }
  })